import { memo, forwardRef, useState, useImperativeHandle, ForwardRefRenderFunction, SetStateAction } from 'react'
import { Modal, Form } from 'antd'
import { HsAdminForm } from '@hs-admin/base-components'
import { addProductCategory, editProductCategory } from '@/api/assetMaintain/dataProduct'
import { message } from '@hs-admin/utils'

interface Props {
  finish: () => void
}
const TableEdit: ForwardRefRenderFunction<unknown, Props> = (props: Props, ref: any) => {
  const { finish } = props
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [form] = Form.useForm()
  const [formValues, setformValues] = useState<any>({})
  const formItemOptions = [
    {
      label: '产品类别名称',
      name: 'name',
      required: true,
      component: 'Input',
      componentProps: {
        maxLength: 10
      }
    },
    {
      label: '产品类别描述',
      name: 'description',
      required: true,
      component: 'TextArea',
      componentProps: {
        autoSize: true
      }
    }
  ]
  const [category, setcategory] = useState('')

  const handleOk = async () => {
    form
      .validateFields()
      .then(async (values) => {
        const params: any = {
          ...formValues,
          ...values,
          category
        }
        let callFn = addProductCategory
        let text = '新增成功'
        if (params.id) {
          callFn = editProductCategory
          text = '编辑成功'
        }
        await callFn(params)
        message.success(text)
        finish()
        handleCancel()
      })
      .catch((error) => {
        return Promise.reject(error)
      })
  }
  const handleCancel = () => {
    form.resetFields()
    setformValues({})
    setIsModalOpen(false)
  }
  const showModal = (item: any, source: SetStateAction<string>) => {
    if (item) {
      form.setFieldsValue(item)
      setformValues(item)
    }
    setcategory(source)
    setIsModalOpen(true)
  }

  useImperativeHandle(
    ref,
    () => {
      return {
        showModal
      }
    },
    []
  )

  return (
    <Modal title="新增/编辑数据产品类别" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
      <HsAdminForm form={form} formItemOptions={formItemOptions} />
    </Modal>
  )
}

export default memo(forwardRef(TableEdit))
